<?php

namespace App\Console\Commands;

use App\Enum\SmsScheduleEnum;
use App\Lib\sms\AliSms;
use App\Models\OrderModel;
use App\Models\ScheduleRecordModel;
use App\Models\SmsScheduleModel;
use App\Services\PublikService;
use Illuminate\Console\Command;

class udpateOrderAddressAdcodeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:fetch-adcode {send_num?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新订单中的adcode';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        while(1) {
            $second = date('s');

            if ($second >= 55) {
                $this->info("second = $second, wait for next time.");
                break;
            }else  $this->info("second = $second, keep going.");

            $sendNum = $this->argument('send_num') ?? 1;

            $record = ScheduleRecordModel::query()->where(['schedule'=>'put_order_adcode'])->first(['record_id','id']);

            $record = $record->toArray();

            $recordId = $record['record_id'];
            $scheduleId = $record['id'];

            $rows = OrderModel::query()->orWhere(['start_adcode'=>'','end_adcode'=>''])->where('id', '>', $recordId)->orWhereNull()
                ->orderBy('id', 'asc')->limit($sendNum)->get()->toArray();

            if (!empty($rows)) {
                $newRecordId = 0;
                foreach ($rows as $row) {
                    $updateData = [];

                    if(empty($row['start_adcode'])) $updateData ['start_adcode']= PublikService::_fetchAdcode($row['start_location']);
                    if(empty($row['end_adcode'])) $updateData ['end_adcode']= PublikService::_fetchAdcode($row['end_location']);
                    if(empty($updateData)) continue;

                    $newRecordId = $row['id'];
                    OrderModel::query()->where(['id'=>$row['id']])->update($updateData);
                }
                echo "\nnew record id=$newRecordId\n";
                if( $newRecordId != 0 )
                    ScheduleRecordModel::query()->where(['id'=>$scheduleId])->update(['record_id'=>$newRecordId]);
            }
            sleep(2);
        }
        //
        return 0;
    }

}
